package com.hzbank.juc.pattern;

import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2023/12/22 - 15:50
 */
@Slf4j
public class GuardedObject2 {
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public GuardedObject2(int id) {
        this.id = id;
    }

    private Object response;
    private Object lock = new Object();

    public Object get(long timeout){
        synchronized (this){
            long begin = System.currentTimeMillis();
            long passTime = 0;
            while (response == null){
                long waitTime = timeout - passTime;
                if (waitTime <= 0) {
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                passTime = System.currentTimeMillis() - begin;
            }
            return response;
        }
    }
    public void complete(Object response){
        synchronized (this){
            this.response = response;
            this.notifyAll();
        }
    }
}

